require 'singleton'
require 'sqlite3'

=begin
Author  : atila camurca
Date    : 08/05/2010
Version : 1.0
Description
   Cria e manipula uma conexão com o SQLite3.
=end
class Connection
  include Singleton
   
  attr_accessor :conn
   
  def initialize
		self
  end

=begin
Author  : atila camurca
Version : 1.0
Return  : #SQLite3::Database
Description
  Verifica se a conexão é nula e retorna uma conexão criada.
=end
  def get_conn
		if @conn.nil?
			create_conn
      foreign_keys_on
		end
		@conn
  end
   
  def create_conn
		@conn = SQLite3::Database.new("../dbase/e-poller.sqlite")
    self
  end

  def foreign_keys_on
    set_boolean_pragma( "foreign_keys", true )
  end

  def close_conn
		unless @conn.nil?
			@conn.close
		end
    @conn = nil
    self
  end

  def set_boolean_pragma( name, mode )
    case mode
    when String
      case mode.downcase
      when "on", "yes", "true", "y", "t"; mode = "'ON'"
      when "off", "no", "false", "n", "f"; mode = "'OFF'"
      else
        raise Exception,
          "unrecognized pragma parameter #{mode.inspect}"
      end
    when true, 1
      mode = "ON"
    when false, 0, nil
      mode = "OFF"
    else
      raise Exception,
        "unrecognized pragma parameter #{mode.inspect}"
    end

    get_conn.execute( "PRAGMA #{name}=#{mode}" )
  end
  
end